﻿using System;
using System.Collections.Generic;

using System.Text;
using Estimate.OldSemiCompare;
using Estimate.Common;
using Estimate.Common.DBFieldTypes;
using Estimate.Common.Entity;
using Estimate.Common.Repository;
using System.Data.SqlClient;

namespace Estimate.OldSemiCompare.Transfer
{
    public class RainRealTransfer :ITranferTableData
    {
        protected string _oldConnectionString;
        protected string _newConnectionString;

        protected RainRealRepository Repository;


        public RainRealTransfer(string oldConnectionString, string newConnectionString) 
        {
            _oldConnectionString = oldConnectionString;
            _newConnectionString = newConnectionString;
            Repository = RainRealRepositoryFactory.ManualRainRealRepository(newConnectionString);
            if (!Repository.IsTableExist())
                Repository.CreateTable();
        }

        public void WriteLog(string e)
        {
            Console.WriteLine(e);
        }

        public string GetTableName()
        {
            return "RainReal";
        }

        public void TransformData(string table)
        {
            string sql = string.Format("SELECT * FROM [{0}]", table);

            SqlConnection connection = new SqlConnection(_oldConnectionString);
            SqlDataReader reader =  DBHelper.ExecuteReader(connection, sql);
            RainRealEntity entity = null;
            while (reader.Read())
            {
                try
                {
                    string strDate = (string)reader["date"].ToString();
                    int year = Convert.ToInt32(strDate.Substring(0, 4));
                    int month = Convert.ToInt32(strDate.Substring(4, 2));
                    int day = Convert.ToInt32(strDate.Substring(6, 2));
                    DateTime date = new DateTime(year, month, day);

                    string strType = reader["type"].ToString().Trim();
                    int intType = Convert.ToInt32(strType);
                    strType = "D" + intType.ToString();
                    RealRainValueType type = (RealRainValueType)Enum.Parse(typeof(RealRainValueType), strType);

                    string value = reader["value"].ToString();

                    entity = new RainRealEntity(date, type, value);
                }
                catch (Exception e)
                {
                    this.WriteLog("\n");
                    this.WriteLog(string.Format("{0}: \n \t id:{1}, \n\t message:{2}", table, reader["id"], e.Message));
                    this.WriteLog("\n");
                    this.WriteLog(string.Format("\t\t date={0}\t, type={1}", reader["date"].ToString(), reader["type"].ToString()));
                    continue;
               
                }
                Repository.SetValue(entity);

            }
            connection.Close();
        }
    }
}
